/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.theorcs.chronicles.model.sheet;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.IndexColumn;
import org.libermundi.theorcs.chronicles.ChronicleConstants;
import org.libermundi.theorcs.chronicles.model.Persona;
import org.libermundi.theorcs.security.model.UserStatefulEntity;

@Entity(name="Sheet")
@Table(name=ChronicleConstants.TBL_SHEET)
public final class Sheet extends UserStatefulEntity {
	private static final long serialVersionUID = 3904128673455703405L;
	
	public static final int WIDTH=960;
	public static final int HEIGHT=1358;
	
	private List<SheetPage> _pages= new ArrayList<>(0);

	private Persona _perso;
	
	@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER,orphanRemoval=true)
	@JoinColumn(name="sheetId")
	@IndexColumn(name = "pagePosition")
	public List<SheetPage> getPages() {
		return _pages;
	}
	
	@OneToOne(mappedBy="sheet")
	public Persona getPersona(){
		return _perso;
	}
	
	@Transient
	public SheetPage getPage(int index) {
		return _pages.get(index);
	}

	public void setPersona(Persona perso){
		_perso = perso;
	}
	
	public void setPage(int index, SheetPage page) {
		_pages.set(index, page);
	}

	public void setPages(List<SheetPage> pages) {
		_pages=pages;
	}

	public void addPage(SheetPage page) {
		_pages.add(page);
	}

	public void addPage(int index, SheetPage page) {
		_pages.add(index, page);	
	}

	public void serializePages() {
		for (Iterator<SheetPage> iterator = _pages.iterator(); iterator.hasNext();) {
			SheetPage page = iterator.next();
			page.serializePage();
		}		
	}

	public void addPage() {
		int newPageIndex = _pages.size() + 1;
		addPage(new SheetPage("Page " + newPageIndex));
	}

}
